import random

from django.http import HttpResponse
from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework import request
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import  APIView
from libs.captcha.captcha import captcha
from libs.yuntongxun.yuntongxun.sms import CCP
from users.models import User

from users.serializer import RegisterSMSCodeSerializer, UserDetailSerializer, EmailSerializer, AddressSerializer
from users.serializer import RegisterUserSerializer
from rest_framework.generics import CreateAPIView


# //TODO
#新增地址后端接口   POST      /users/addresses/

class AddressAPIView(CreateAPIView):


    permission_classes = [IsAuthenticated]
    serializer_class = AddressSerializer


    #由于用户的地址有存在删除的状态,所以我们需要对数据进行筛选
    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)
    #少了user_id
    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        count = request.user.addresses.count()
        if count >= 20:
            return Response({'message':'保存地址数量已经达到上限'},status=status.HTTP_400_BAD_REQUEST)

        return super().create(request,*args,**kwargs)

    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': 20,
            'addresses': serializer.data,
        })

    def destroy(self, request, *args, **kwargs):
        address = self.get_object()
        address.is_deleted = True
        address.save()
        return Response(status=status.HTTP_204_NO_CONTENT)




#激活接口  GET /users/emails/verification/
from users.utils import check_verify_email_token


class VerificationEmailView(APIView):
    def get(self,request):
        data = request.query_params
        token = data.get('token')
        if not token:
            return Response({'message': '没有拼token'}, status=status.HTTP_400_BAD_REQUEST)
        id =check_verify_email_token(token)
        try:
            user =User.objects.get(pk = id)
        except Exception as e:
            return Response({'message': 'token过期'}, status=status.HTTP_400_BAD_REQUEST)

        user.email_active = True
        user.save()
        return Response({'message': 'OK'})

#写入邮箱
class EmailView(APIView):

    permission_classes = [IsAuthenticated]
    def put(self,request):
        data = request.data
        user = request.user
        s = EmailSerializer(instance=user,data=data)
        s.is_valid()
        s.save()
        return Response(s.data)



#个人中心显示数据   GET/users/infos/
class UserDetailView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self,request):
        user = request.user
        serializer = UserDetailSerializer(user)
        data = serializer.data
        return Response(data)



#注册接口  POST/users/
class RegisterUserAPIView(APIView):
    def post(self,request):
        # 1. 接收数据
        data = request.data
        # 2. 校验数据  序列化器
        serializer = RegisterUserSerializer(data = data)
        serializer.is_valid(raise_exception=True)
        # 3. 数据入库
        serializer.save()
        # 4. 返回相应
        return Response(serializer.data)



"""
当用户注册成功之后,自动实现登陆

因为我们现在是采用的 JWT-Token
也就是说 用户注册成功之后 我们应该返回一个token给相应,同时
浏览器把接收到的token保存起来

用户注册成功之后 我们应该返回一个token

# 序列化的时候 多一个token
# 序列化器根据序列化器的字段  token  来获取模型  token 中数据
"""



#验证手机号是否存在 GET方法   GET /users/phones/(?P<mobile>1[345789]\d{9})/count/
class RegisterMobileCountAPIView(APIView):
    def get(self,request,mobile):
        mobile_count = User.objects.filter(mobile = mobile).count()
        data = {
            'count': mobile_count,
            'mobile': mobile,
        }
        return  Response(data=data)



#验证用户名是否存在   GET方法
class RegisterUsernameCountAPIView(APIView):
    """
    GET:  /users/usernames/(?P<username>\w{5,20})/count/
    1.接收参数
    2.去数据库查询
    """
    #1.接收参数
    def get(self,request,username):
        #2.去数据库查询
        username_count =User.objects.filter(username = username).count()
        data ={
            'count':username_count,
            'username':username,
        }
        return Response(data=data,)


